package com.jwsoft.manager.core.dao.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.jwsoft.manager.common.enums.MatchingStatusEnum;
import com.jwsoft.manager.common.vo.bigScreen.analysisXq.AddressOverviewXqQueryVO;
import com.jwsoft.manager.common.vo.bigScreen.analysisXq.SchoolAddressCountVO;
import com.jwsoft.manager.common.vo.bigScreen.analysisXq.StuEnrollDgxxInVO;
import com.jwsoft.manager.common.vo.bigScreen.analysisXq.StuEnrollXxhxXqnxqVO;
import com.jwsoft.manager.common.vo.eduAddress.EduAddressVO;
import com.jwsoft.manager.common.vo.eduAddress.SchoolAddressQueryVO;
import com.jwsoft.manager.common.vo.eduAddressSchool.EduAddressSchoolQueryVO;
import com.jwsoft.manager.common.vo.eduAddressSchool.EduAddressSchoolSearchVO;
import com.jwsoft.manager.common.vo.eduAddressSchool.EduAddressSchoolVO;
import com.jwsoft.manager.common.vo.eduAddressSchoolAudit.EduAddressSchoolAuditVO;
import com.jwsoft.manager.common.vo.eduAddressTreeInitial.EduAddressTreeInitialVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.common.vo.eduSchool.SchoolDistrictQueryVO;
import com.jwsoft.manager.common.vo.eduSchool.SchoolDistrictVO;
import com.jwsoft.manager.core.dao.mapper.EduAddressSchoolMapper;
import com.jwsoft.manager.core.dao.mapper.EduAddressTreeMapper;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.eduAddressTree.impl.AddressTree;
import com.jwsoft.manager.core.util.EduEnrollClearCacheHelper;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 地址学校关联表服务实现类
 *
 * @author wangtao
 * @since 2022-12-02
 */
@Service
public class EduAddressSchoolServiceImpl extends ServiceImpl<EduAddressSchoolMapper, EduAddressSchool> implements EduAddressSchoolService {
    @Autowired
    private EduAddressService eduAddressService;
    @Autowired
    private EduSchoolService eduSchoolService;
    @Autowired
    private EduAddressTreeMapper eduAddressTreeMapper;
    @Autowired
    private EduAddressCategoryService eduAddressCategoryService;
    @Autowired
    public EduAddressTreeInitialService addressTreeInitialService;

    @Autowired
    public EduAddressTreeService addressTreeService;

    @Autowired
    private CommonIntegration commonIntegration;

    @Autowired
    private EduAddressTreeSchoolService eduAddressTreeSchoolService;
    @Autowired
    private EduHouseholdService householdService;
    @Autowired
    private EduHouseService houseService;

    @Autowired
    private EduHelper eduHelper;

    @Autowired
    private EduHouseDetailService houseDetailService;

    @Autowired
    private EduStudentEnrollPreService studentEnrollPreService;
    @Autowired
    private EduEnrollClearCacheHelper eduEnrollClearCacheHelper;

    @Override
    public List<EduAddressVO> getAddressNo(SchoolAddressQueryVO vo) {
        return this.baseMapper.getAddressNo(vo);
    }

    @Override
    public List<SchoolDistrictVO> getSchoolInfo(SchoolDistrictQueryVO vo) {
        return this.baseMapper.getSchoolInfo(vo);
    }

    @Override
    public List<EduAddressVO> getAddress(SchoolAddressQueryVO vo) {
        return this.baseMapper.getAddress(vo);
    }
    @Override
    public List<SchoolAddressCountVO> getSchoolAddressCountVO(AddressOverviewXqQueryVO vo) {
        return this.baseMapper.getSchoolAddressCountVO(vo);
    }

    @Override
    public List<EduAddressSchoolVO> getAddressByGl(EduAddressSchoolSearchVO vo) {
        return this.baseMapper.getAddressByGl(vo);
    }

    @Override
    public List<EduAddressSchoolVO> getAddressByNoGl(EduAddressSchoolSearchVO vo) {
        return this.baseMapper.getAddressByNoGl(vo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String bound(String addressId, String schoolId) {
        //先判断表中，是否有关联数据
        QueryWrapper<EduAddressSchool> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(EduAddressSchool::getAddressId, addressId)
                .eq(EduAddressSchool::getSchoolId, schoolId);
        EduAddressSchool eduAddressSchool = getOne(wrapper);
        if (eduAddressSchool != null) {
            return eduAddressSchool.getAddressSchoolId();
        }
        EduSchoolVO eduSchool = eduSchoolService.getDetail(schoolId);
        if (eduSchool == null) {
            throw new RuntimeException(String.format("未查询到对应的学校信息，id:%s", schoolId));
        }
        EduAddress address = eduAddressService.getById(addressId);
        if (address == null) {
            throw new RuntimeException(String.format("未查询到对应的地址信息，id:%s", addressId));
        }
        eduAddressSchool = new EduAddressSchool();
        eduAddressSchool.setAddressId(address.getAddressId());
        eduAddressSchool.setAddressName(address.getAddressName());
        eduAddressSchool.setSchoolId(eduSchool.getOrgId());
        eduAddressSchool.setSchoolName(eduSchool.getSchoolName());
        eduAddressSchool.setSchoolCategory(eduSchool.getSchoolCategory());
//        eduAddressSchool.setServiceAreaFlag(eduSchool.getServiceAreaFlag());
        eduAddressSchool.setTreeId(address.getAddressTreeId());
        eduAddressSchool.setCreateName(SessionUtil.getUserId());
        eduAddressSchool.setAreaCode(eduSchool.getAreaCode());
        eduAddressSchool.setCreateTime(new Date());
        this.baseMapper.insert(eduAddressSchool);
        if (address.getAddressTreeId() != null) {
            EduAddressTree eduAddressTree = eduAddressTreeMapper.selectById(address.getAddressTreeId());
            if (eduAddressTree != null) {
                AddressTree addressTree = AddressTree.getAddressTree(eduAddressTree);
                addressTree.boundSchool(eduSchool);
            }
        }
        //检查该地址其他审核数据，修改地址-学段表
        try {
            eduAddressCategoryService.checkAndUpdate(addressId, eduSchool.getSchoolCategory());
        } catch (Exception e) {
            throw new AppException("地址-学段状态修改异常", e);
        }
        return eduAddressSchool.getAddressSchoolId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unbound(String addressId, String schoolId) {
        //先判断表中，是否有关联数据
        QueryWrapper<EduAddressSchool> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(EduAddressSchool::getAddressId, addressId)
                .eq(EduAddressSchool::getSchoolId, schoolId);
        EduAddressSchool eduAddressSchool = this.getOne(wrapper);
        if (eduAddressSchool == null) {
            return;
        }
        EduSchoolVO schoolVO = eduSchoolService.getDetail(schoolId);
        if (schoolVO == null) {
            throw new RuntimeException(String.format("未查询到对应的学校信息，id:%s", schoolId));
        }
        EduAddress eduAddress = eduAddressService.getById(addressId);
        if (eduAddress.getAddressTreeId() != null) {
            EduAddressTree eduAddressTree = eduAddressTreeMapper.selectById(eduAddress.getAddressTreeId());
            if (eduAddressTree != null) {
                AddressTree addressTree = AddressTree.getAddressTree(eduAddressTree);
                addressTree.unboundSchool(schoolVO);
            }
        }
        this.removeById(eduAddressSchool.getAddressSchoolId());
        //检查该地址其他审核数据，修改地址-学段表
        try {
            eduAddressCategoryService.checkAndUpdate(addressId, schoolVO.getSchoolCategory(), true);
        } catch (Exception e) {
            throw new AppException("地址-学段状态修改异常", e);
        }
    }

    /**
     * 绑定地址和学校关联
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String boundSchoolAndAddress(EduAddressSchoolAuditVO vo) {
        if (StringUtils.isEmpty(vo.getAddressId())){
            throw new RuntimeException("地址id不能为空");
        }
        if (StringUtils.isEmpty(vo.getSchoolId())){
            throw new RuntimeException("学校id不能为空");
        }
        if (StringUtils.isEmpty(vo.getNativeFlag())){
            vo.setNativeFlag("0");
        }
        if (StringUtils.isEmpty(vo.getServiceAreaFlag())){
            vo.setServiceAreaFlag("0");
        }
        if (StringUtils.isBlank(vo.getVerificationFlag())) {
            vo.setVerificationFlag(BoolEnum.FALSE.getType());
        }

        //先判断表中，是否有关联数据
        QueryWrapper<EduAddressSchool> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(EduAddressSchool::getAddressId, vo.getAddressId())
                .eq(EduAddressSchool::getSchoolId, vo.getSchoolId());
        EduAddressSchool eduAddressSchool = getOne(wrapper);
        if (eduAddressSchool != null) {
            return eduAddressSchool.getAddressSchoolId();
        }
        EduSchoolVO eduSchool = eduSchoolService.getDetail(vo.getSchoolId());
        if (eduSchool == null) {
            throw new RuntimeException(String.format("未查询到对应的学校信息，id:%s", vo.getSchoolId()));
        }
        EduAddress address = eduAddressService.getById(vo.getAddressId());
        if (address == null) {
            throw new RuntimeException(String.format("未查询到对应的地址信息，id:%s", vo.getAddressId()));
        }
        eduAddressSchool = new EduAddressSchool();
        eduAddressSchool.setAddressId(address.getAddressId());
        eduAddressSchool.setAddressName(address.getAddressName());
        eduAddressSchool.setSchoolId(eduSchool.getOrgId());
        eduAddressSchool.setSchoolName(eduSchool.getSchoolName());
        eduAddressSchool.setSchoolCategory(eduSchool.getSchoolCategory());
        eduAddressSchool.setNativeFlag(vo.getNativeFlag());
        eduAddressSchool.setServiceAreaFlag(vo.getServiceAreaFlag());
        eduAddressSchool.setTreeId(address.getAddressTreeId());
        eduAddressSchool.setCreateName(SessionUtil.getUserId());
        eduAddressSchool.setAreaCode(eduSchool.getAreaCode());
        eduAddressSchool.setAuthStatus(AuthStatusEnum.YES.getType());
        eduAddressSchool.setAuthTime(new Date());
        eduAddressSchool.setAuthUserId(SessionUtil.getUserId());
        eduAddressSchool.setCreateTime(new Date());
        eduAddressSchool.setVerificationFlag(vo.getVerificationFlag());
        eduAddressSchool.setAuditId(vo.getId());
        eduAddressSchool.setAuditAuto(vo.getAuditAuto());//如果自动审核，会传过来1，表示自动审核
        this.baseMapper.insert(eduAddressSchool);
        if (address.getAddressTreeId() != null) {
            EduAddressTreeInitial lastNode = new EduAddressTreeInitial();
            //校验参数：是否去tree表查询数据  1去树表查询 0 去初始化表查询
            CommonVO addressParseCheck = new CommonVO();
            addressParseCheck.setParamKey("TREE_OR_INITIAL_FLAG");
            String treeOrInitialFlag = commonIntegration.getValueByKey(addressParseCheck);
            if (StringUtils.isBlank(treeOrInitialFlag)){
                treeOrInitialFlag = BoolEnum.TRUE.getType();
            }
            if (BoolEnum.TRUE.getType().equals(treeOrInitialFlag)) {
                EduAddressTree addressTree = addressTreeService.getById(address.getAddressTreeId());
                lastNode = Convert.convert(EduAddressTreeInitial.class, addressTree);
            }else{
                lastNode = addressTreeInitialService.getById(address.getAddressTreeId());
            }
            if (lastNode != null){
                //将地址树节点和学校进行关联
                EduAddressTreeInitialVO lastInitialVO=Convert.convert(EduAddressTreeInitialVO.class,lastNode);
                 this.saveTreeSchoolRelation(address, lastInitialVO);
            }
        }
        //据地址id，更新预采集中的预报名状态
        this.renewalBeforeFlagByAddressId(vo.getAddressId());
        return eduAddressSchool.getAddressSchoolId();
    }

    @Override
    public List<StuEnrollXxhxXqnxqVO> getStuEnrollXxhxXqnxq(StuEnrollDgxxInVO vo) {
        return this.baseMapper.getStuEnrollXxhxXqnxq(vo);
    }

    /**
     * 解析好的地址树需要初始化学区关联
     * @param eduAddress 地址数据
     * @param lastNode  最后一个节点信息
     */
    @Override
    public void saveTreeSchoolRelation(EduAddress eduAddress, EduAddressTreeInitialVO lastNode) {
        if (ObjectUtils.isEmpty(lastNode) || ObjectUtils.isEmpty(eduAddress)){
            return;
        }
        //判断地址是否关联了学区信息
        QueryWrapper<EduAddressSchool> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduAddressSchool::getAddressId, eduAddress.getAddressId());
        long relationCount = this.count(queryWrapper);
        if (relationCount == 0 ){
            eduAddress.setMatchingStatus(MatchingStatusEnum.NODO.getType());
            eduAddress.setMatchingMessage(MatchingStatusEnum.NODO.getName());
            eduAddress.setMatchingTime(new Date());
            return;
        }
        //有学校关联，在进行初始化学区
        eduAddress.setMatchingStatus(MatchingStatusEnum.SUCCESS.getType());
        eduAddress.setMatchingMessage(MatchingStatusEnum.SUCCESS.getName());
        eduAddress.setMatchingTime(new Date());
        List<EduAddressSchool> relationList = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(relationList)){
            return;
        }
        //校验参数：是否去tree表查询数据  1去树表查询 0 去初始化表查询
        CommonVO addressParseCheck = new CommonVO();
        addressParseCheck.setParamKey("TREE_OR_INITIAL_FLAG");
        String treeOrInitialFlag = commonIntegration.getValueByKey(addressParseCheck);
        if (StringUtils.isBlank(treeOrInitialFlag)){
            treeOrInitialFlag = BoolEnum.TRUE.getType();
        }
        List<EduAddressTree> treeLink = new ArrayList<>();
        if (BoolEnum.TRUE.getType().equals(treeOrInitialFlag)){
            //根据最后一个节点，树形节点链路信息（到街道位置 town）
           treeLink = addressTreeService.getLinkByTreeId(lastNode.getAddressId());
        }else{
            //根据最后一个节点，树形节点链路信息（到街道位置 town）
            List<EduAddressTreeInitial> treeInitialList = addressTreeInitialService.getLinkByTreeId(lastNode.getAddressId());
            treeLink = Convert.toList(EduAddressTree.class, treeInitialList);
        }
        if (treeLink.size() == 0){
            return;
        }
        for (EduAddressSchool eduAddressSchool : relationList) {
            List<EduAddressTreeSchool> treeSchoolList = treeLink.stream().filter(item ->{
                EduSchoolVO school = eduSchoolService.getDetail(eduAddressSchool.getSchoolId());
                if (!ObjectUtils.isEmpty(school)){
                    return true;
                }
                return false;
            }).map(item -> {
                EduSchoolVO school = eduSchoolService.getDetail(eduAddressSchool.getSchoolId());
                EduAddressTreeSchool treeSchool = new EduAddressTreeSchool();
                treeSchool.setSchoolId(school.getOrgId());
                treeSchool.setTreeId(item.getAddressId());
                treeSchool.setSchoolCategory(school.getSchoolCategory());
                treeSchool.setSchoolNature(school.getSchoolNature());
                treeSchool.setSchoolName(school.getSchoolName());
                treeSchool.setShortName(school.getShortName());
                treeSchool.setAreaCode(school.getAreaCode());
                treeSchool.setSchoolNum(school.getSchoolNum());
                return treeSchool;
            }).filter(item ->{
                //根据treeId 和SchoolId去查数据库，判断是否存在
                long count = eduAddressTreeSchoolService.count(Wrappers.<EduAddressTreeSchool>lambdaQuery()
                        .eq(EduAddressTreeSchool::getTreeId, item.getTreeId())
                        .eq(EduAddressTreeSchool::getSchoolId, item.getSchoolId()));
                if (count == 0){
                    return true;
                }else{
                    return false;
                }
            }).collect(Collectors.toList());
            try {
                //1.保存树节点和学校关联
                eduAddressTreeSchoolService.saveBatch(treeSchoolList);
                //2.更新地址和学校关联表中treeId
                eduAddressSchool.setTreeId(lastNode.getAddressId());
                updateById(eduAddressSchool);
            } catch (Exception e) {
                throw new AppException("保存地址树和学校关联发生异常：e:"+e.getMessage());
            }

            //根据treeId和schoolId去查询学校树关联表，如果存在，则更新服务区和正学区
            // 1. 获取服务区标志和正学区标志
            String serviceAreaFlag = eduAddressSchool.getServiceAreaFlag();
            String nativeFlag = eduAddressSchool.getNativeFlag();
            String schoolId = eduAddressSchool.getSchoolId();
            // 2. 收集 treeId
            List<Long> treeIds = treeLink.stream()
                    .map(EduAddressTree::getAddressId)
                    .collect(Collectors.toList());
            // 3. 构建查询条件，查找关联的学校树记录
            List<EduAddressTreeSchool> addressTreeSchools = eduAddressTreeSchoolService.list(
                    new QueryWrapper<EduAddressTreeSchool>()
                            .lambda()
                            .in(EduAddressTreeSchool::getTreeId, treeIds)
                            .eq(EduAddressTreeSchool::getSchoolId, schoolId)
            );
            // 4. 批量更新服务区标志和正学区标志
            addressTreeSchools.forEach(treeSchool -> {
                treeSchool.setNativeFlag(nativeFlag);
                treeSchool.setServiceAreaFlag(serviceAreaFlag);
            });
            // 5. 批量更新数据库
            if (!addressTreeSchools.isEmpty()) {
                eduAddressTreeSchoolService.updateBatchById(addressTreeSchools);
            }
        }
    }

    /**
     * 解绑学校和地址信息
     * @param addressId  地址主键
     * @param schoolId 学校主键
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unboundSchoolAndAddress(String addressId, String schoolId) {
        //先判断表中，是否有关联数据
        QueryWrapper<EduAddressSchool> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(EduAddressSchool::getAddressId, addressId)
                .eq(EduAddressSchool::getSchoolId, schoolId);
        EduAddressSchool eduAddressSchool = this.getOne(wrapper,false);
        if (eduAddressSchool == null) {
            return;
        }
        EduSchoolVO schoolVO = eduSchoolService.getDetail(schoolId);
        if (schoolVO == null) {
            throw new RuntimeException(String.format("未查询到对应的学校信息，id:%s", schoolId));
        }
        EduAddress eduAddress = eduAddressService.getById(addressId);
        //判断最后一个树节点id是否存在
        if (eduAddress.getAddressTreeId() != null) {
            EduAddressTree eduAddressTree = eduAddressTreeMapper.selectById(eduAddress.getAddressTreeId());
            if (eduAddressTree != null) {
                List<EduAddressTree> treeNodes = addressTreeService.getLinkByTreeId(eduAddress.getAddressTreeId());
                //解绑edu_address_tree_school中的关联信息
                eduAddressTreeSchoolService.
                        removeSchoolAndAddressTreeRelation(eduAddressSchool.getSchoolId(),treeNodes);
            }
        }
        //根据地址id，更新预采集中的预报名状态
        this.renewalBeforeFlagByAddressId(addressId);
        //将地址年份标志设置为当前报名年份
        if (eduAddress.getYear() != null){
            Integer year = eduHelper.thisYear();
            if (!year.equals(eduAddress.getYear())){
                eduAddress.setYear(year);
                eduAddressService.updateById(eduAddress);
            }
        }
        //将学校关联数据解析删除
        this.removeById(eduAddressSchool.getAddressSchoolId());

    }


    /**
     * 学校本年度地址库查询
     * @param vo
     * @return
     */
    @Override
    public List<EduAddressSchool> querySchoolAddressByNowYear(EduAddressSchoolQueryVO vo) {
        return baseMapper.querySchoolAddressByNowYear(vo);
    }

    /**
     * 根据地址id，更新预采集中的预报名状态
     * @param addressId
     */
    @Override
    public void renewalBeforeFlagByAddressId(String addressId) {
        if (ObjectUtils.isEmpty(addressId)){
            return;
        }
        EduAddress eduAddress = eduAddressService.getById(addressId);
        if (ObjectUtils.isEmpty(eduAddress)){
            return;
        }

        Integer year = eduHelper.thisYear();
        //定义一个不重复集合，存储身份证信息
        Set<String> idcardList = new HashSet<>();
        //根据地址id查询当年招生年度户籍信息
        QueryWrapper<EduHousehold> householdQueryWrapper = new QueryWrapper<>();
        householdQueryWrapper.lambda().select(EduHousehold::getIdcard)
                .eq(EduHousehold::getAddressId,addressId)
                .eq(EduHousehold::getYear,year);
        //获取户籍地址对应地址数据
        List<EduHousehold> householdList = householdService.list(householdQueryWrapper);
        if (!CollectionUtils.isEmpty(householdList)){
            List<String> householdIdcard = householdList.stream().map(EduHousehold::getIdcard).collect(Collectors.toList());
            idcardList.addAll(householdIdcard);
        }
        //根据地址id获取当年招生年度房产信息
        QueryWrapper<EduHouse> houseQueryWrapper = new QueryWrapper<>();
        houseQueryWrapper.lambda()
                .select(EduHouse::getHouseId)
                .eq(EduHouse::getAddressId, addressId)
                .eq(EduHouse::getYear,year);
        //获取房产地址所对应房产数据
        List<EduHouse> houseList = houseService.list(houseQueryWrapper);
        if (!CollectionUtils.isEmpty(houseList)){
            List<String> houseIds = houseList.stream().map(EduHouse::getHouseId).collect(Collectors.toList());
            QueryWrapper<EduHouseDetail> detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.lambda().select(EduHouseDetail::getHouseDetailId,EduHouseDetail::getIdcard)
                    .in(EduHouseDetail::getHouseId,houseIds).eq(EduHouseDetail::getYear,year);
            List<EduHouseDetail> detailList = houseDetailService.list(detailQueryWrapper);
            if (!CollectionUtils.isEmpty(detailList)){
                //detailList中获取idcard集合，去重，去空值
                for (EduHouseDetail eduHouseDetail : detailList) {
                    if (StringUtils.isBlank(eduHouseDetail.getIdcard())){
                        continue;
                    }
                    if (!idcardList.contains(eduHouseDetail.getIdcard())){
                        idcardList.add(eduHouseDetail.getIdcard());
                    }
                }
            }
        }
        if (CollectionUtils.isEmpty(idcardList)){
            return;
        }

        //根据身份证集合，去查询当年预采集数据
        QueryWrapper<EduStudentEnrollPre> preQueryWrapper = new QueryWrapper<>();
        preQueryWrapper.lambda().select(EduStudentEnrollPre::getStudentEnrollPreId)
                .eq(EduStudentEnrollPre::getBeforeFlag,BoolEnum.TRUE.getType())
                .eq(EduStudentEnrollPre::getYear,year)
                .and(wrapper -> wrapper
                        //查出matchingStatus = 0 或者为null的地址信息
                        .in(EduStudentEnrollPre::getIdcard, idcardList)
                        .or()
                        .in(EduStudentEnrollPre::getFatherIdcard,idcardList)
                        .or()
                        .in(EduStudentEnrollPre::getMotherIdcard,idcardList)
                );
        List<EduStudentEnrollPre> preList = studentEnrollPreService.list(preQueryWrapper);
        if (CollectionUtils.isEmpty(preList)){
            return;
        }
        List<String> preIds = preList.stream().map(EduStudentEnrollPre::getStudentEnrollPreId).collect(Collectors.toList());
        UpdateWrapper<EduStudentEnrollPre> preUpdateWrapper = new UpdateWrapper<>();
        preUpdateWrapper.lambda().in(EduStudentEnrollPre::getStudentEnrollPreId,preIds)
                .set(EduStudentEnrollPre::getConsistentFlag,BoolEnum.FALSE.getType())
                .set(EduStudentEnrollPre::getBeforeFlag,BoolEnum.FALSE.getType());
        studentEnrollPreService.update(preUpdateWrapper);
        for(String preId:preIds){
            //清除缓存
            eduEnrollClearCacheHelper.clearCachePreBefore(preId);
        }
    }
}
